<!-- 商品发布 - 库存价格 -->
<template>
  <el-form ref="formRef" :disabled="isDetail" :model="formData" :rules="rules" label-width="120px">
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span
        ><DictText
          :type="DICT_TYPE[`PRODUCT_SPU_TYPE4`]"
          :value="formData!.skus![0]!.skuType"
        />规则
      </span>
    </div>
    <section v-for="(item, index) in formData!.skus" :key="index">
      <div class="flex flex-wrap">
        <el-form-item
          label="零售价"
          class="w-480px!"
          :prop="`skus[${index}][price]`"
          :rules="rules.price"
        >
          <el-input
            v-model="item.price"
            class="w-100%!"
            :formatter="(value: string) => verifyNumberIntegerAndFloat(value)"
          >
            <template #append>
              <span>元</span>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="成本价" class="w-480px!">
          <el-input
            v-model="item.costPrice"
            class="w-100%!"
            :formatter="(value: string) => verifyNumberIntegerAndFloat(value)"
          >
            <template #append>
              <span>元</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="储值卡金额"
          :prop="`skus[${index}][cardValue]`"
          :rules="rules.cardValue"
          class="w-480px!"
        >
          <template #label>
            <DictText
              :type="DICT_TYPE[`PRODUCT_SPU_TYPE4`]"
              :value="formData!.skus![0]!.skuType"
            />金额
          </template>
          <el-input
            v-model="item.cardValue"
            class="w-100%!"
            :disabled="formData!.spuId != undefined"
            :formatter="(value: string) => verifyNumberIntegerAndFloat(value)"
          >
            <template #append>
              <span>元</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="有效期"
          :prop="`skus[${index}][expiryDate]`"
          :rules="rules.expiryDate"
          class="w-480px!"
        >
          <el-input
            v-model="item.expiryDate"
            :disabled="item.expiryDateUnit == 3 || formData!.spuId != undefined"
          >
            <template #append>
              <el-select v-model="item.expiryDateUnit" placeholder="Select" class="w-60px!">
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.SPU_CARD_DATE_UNIT)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="是否赠金" class="w-480px!">
          <el-select
            v-model="item.isGift"
            placeholder="请选择"
            class="w-100%!"
            :disabled="formData!.spuId != undefined"
          >
            <el-option label="否" :value="false" />
            <el-option label="是" :value="true" />
          </el-select>
        </el-form-item>
        <el-form-item
          label="赠送金额"
          :prop="`skus[${index}][giftValue]`"
          :rules="rules.giftValue"
          class="w-480px!"
          v-if="item.isGift"
        >
          <el-input
            v-model="item.giftValue"
            :disabled="formData!.spuId != undefined"
            :formatter="(value: string) => verifyNumberIntegerAndFloat(value)"
            class="w-100%!"
          >
            <template #append>
              <span>元</span>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item
          label="扣款优先"
          :prop="`skus[${index}][dedLevel]`"
          :rules="rules.dedLevel"
          class="w-480px!"
          v-if="item.isGift"
        >
          <el-select
            v-model="item.dedLevel"
            :disabled="formData!.spuId != undefined"
            placeholder="请选择"
            class="w-100%!"
          >
            <el-option
              v-for="dict in getIntDictOptions(DICT_TYPE.STORED_VALUE_CARD_DEDLEVEL)"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
      </div>
      <el-form-item label="属性">
        <template #label>
          <DictText
            :type="DICT_TYPE[`PRODUCT_SPU_TYPE4`]"
            :value="formData!.skus![0]!.skuType"
          />属性
        </template>
        <div>
          <el-checkbox-group
            v-model="item.useDiscountType"
            :disabled="formData!.spuId != undefined"
          >
            <template
              v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_USE_DISCOUNT_TYPE)"
              :key="dict.value"
            >
              <el-checkbox
                :value="dict.value"
                v-if="dict.value == 0"
                :disabled="item.useDiscountType?.includes(1) || item.useDiscountType?.includes(2)"
              >
                {{ dict.label }}
              </el-checkbox>
              <el-checkbox :value="dict.value" v-else :disabled="item.useDiscountType?.includes(0)">
                {{ dict.label }}
              </el-checkbox>
            </template>
          </el-checkbox-group>

          <Explaintip :msg="'折扣类型优先级： 指定商品 > 指定类型 > 全部商品'" />
        </div>
      </el-form-item>
      <el-form-item label="折扣比例" class="w-480px!" v-if="item.useDiscountType?.includes(0)">
        <el-input
          v-model="item.allDiscount"
          class="w-100%!"
          :disabled="formData!.spuId != undefined"
          :formatter="(value: string) => verifyNumberPercentage(value)"
        >
          <template #append>
            <span>%</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="商品类型" class="w-480px!" v-if="item.useDiscountType?.includes(1)">
        <ProductSpuTypeSelect
          ref="SpuTypeSelectRef"
          v-model="typeDiscountGoods"
          @change="typeDiscountGoodsChange"
        />
      </el-form-item>
      <el-form-item v-if="typeDiscountGoods?.length > 0 && item.useDiscountType?.includes(1)">
        <div class="flex flex-wrap">
          <div v-for="(typeDiscountItem, index) in typeDiscountGoods" :key="index">
            <el-table border :data="[typeDiscountItem]">
              <el-table-column label="商品类型" align="center" min-width="168">
                <template #default="scope">
                  <span>{{ getSputTypeInfo(scope.row) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="折扣比例" align="center" min-width="168">
                <template #default="scope">
                  <el-form
                    :model="formData.skus![0].appointTypeDiscount[scope.row]"
                    :disabled="isDetail"
                  >
                    <el-form-item prop="discountRatio">
                      <el-input
                        :disabled="formData!.spuId != undefined"
                        v-model.number="formData.skus![0].appointTypeDiscount[scope.row].discount"
                        :formatter="(value: string) => verifyNumberPercentage(value)"
                        placeholder="请输入"
                      >
                        <template #append>
                          <span>%</span>
                        </template>
                      </el-input>
                    </el-form-item>
                  </el-form>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </el-form-item>
      <el-form-item label="指定商品" v-if="item.useDiscountType?.includes(2)">
        <GiveGoodsForm
          v-model="item.appointSkusDiscount"
          :scene-type="'discount'"
          ref="discountGiveGoodsFormRef"
          :is-detail="isDetail"
          @error-info="setgiveGoodsFormErrorInfo"
        />
      </el-form-item>
      <el-form-item label="赠金到账" class="w-480px!" v-if="item.isGift">
        <el-select
          v-model="item.giftAccountType"
          placeholder="请选择"
          :disabled="formData!.spuId != undefined"
          class="w-100%!"
        >
          <el-option label="一次到账" :value="0" />
          <!-- <el-option label="周期到账" :value="1" /> -->
        </el-select>
      </el-form-item>
      <el-form-item label="到账设置" class="w-480px!" v-if="item.giftAccountType == 1">
        <div>
          <el-radio-group
            v-model="item.giftAccountDType"
            :disabled="formData!.spuId != undefined"
            @change="giftAccountDTypeChange(item)"
          >
            <el-radio :value="0">统一设置</el-radio>
            <el-radio :value="1">单一设置</el-radio>
          </el-radio-group>
          <Explaintip v-if="item.giftAccountDType == 0" msg="即赠金多次均分固定时间到账" />
          <Explaintip v-if="item.giftAccountDType == 1" msg="即赠金多次固定金额固定时间分批到账" />
        </div>
      </el-form-item>
      <el-form-item label="到账日期" class="w-480px!" v-if="item.giftAccountDType == 0">
        <el-select
          v-model="item.giftAccountSet![0].intoAccountDateDay"
          placeholder="到账日期"
          :disabled="formData!.spuId != undefined"
          class="w-100%"
        >
          <el-option
            v-for="(item, index) in monthGiveRollDateOptions"
            :key="'dzhang' + index"
            :value="item.value"
            >{{ item.label }}</el-option
          >
        </el-select>
      </el-form-item>
      <el-form-item label="到账金额" class="w-480px!" v-if="item.giftAccountDType == 0">
        <el-input
          v-model="item.giftAccountSet![0].intoAccountMoney"
          :disabled="formData!.spuId != undefined"
          class="w-100%!"
        >
          <template #append>
            <span>元</span>
          </template>
        </el-input>
      </el-form-item>
      <el-form-item label="单一设置" v-if="item.giftAccountDType == 1">
        <div>
          <el-button @click="giftAccountDTypeAdd(item.giftAccountSet)"> 新增 </el-button>
          <el-table class="mt20px" border :data="item.giftAccountSet">
            <el-table-column label="到账时间" :align="'center'" min-width="168">
              <template #default="{ row }">
                <span
                  >购买后第
                  <el-input-number
                    v-model="row.intoAccountDateMonth"
                    :disabled="formData!.spuId != undefined"
                    :precision="0"
                    :step="1"
                    placeholder="X"
                    :controls="false"
                    class="w-60px!"
                  />个月</span
                >
              </template>
            </el-table-column>
            <el-table-column min-width="168" :align="'center'" label="到账日期">
              <template #default="{ row }">
                <el-form-item>
                  <el-input-number
                    v-model="row.intoAccountDateDay"
                    :disabled="formData!.spuId != undefined"
                    :precision="0"
                    :step="1"
                    :min="1"
                    :max="31"
                    placeholder="日期"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column min-width="168" :align="'center'" label="到账金额">
              <template #default="{ row }">
                <el-form-item>
                  <el-input
                    v-model.number="row.intoAccountMoney"
                    :disabled="formData!.spuId != undefined"
                    placeholder="请输入"
                  >
                    <template #append>
                      <span>元</span>
                    </template>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="title" label="操作" :align="'center'" width="120">
              <template #default="{ $index }">
                <el-button
                  text
                  :disabled="isDetail || formData!.spuId != undefined"
                  type="primary"
                  @click="giftAccountDTypeDelete(item.giftAccountSet, $index)"
                >
                  移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form-item>

      <!-- <el-form-item label="关联商品">
        <GiveGoodsForm
          :show-type="'number'"
          v-model="item.giveGoods"
          ref="GiveGoodsFormRef"
          @error-info="setgiveGoodsFormErrorInfo"
        />
      </el-form-item> -->
    </section>
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>分销设置 </span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px">
        如商品仅有一个规格请使用单规格；如有容量、颜色等多种规格，请使用多规格。
      </span>
    </div>
    <el-form-item label="分销开关" props="subCommissionEnable">
      <el-switch
        v-model="formData.subCommissionEnable"
        @change="changeSubCommissionEnable"
      ></el-switch>
    </el-form-item>
    <el-form-item label="分销类型" props="subCommissionType" v-if="formData.subCommissionEnable">
      <el-radio-group
        v-model="formData.subCommissionType"
        class="w-80"
        @change="changeSubCommissionType"
      >
        <el-radio :value="false">默认设置</el-radio>
        <el-radio :value="true" class="radio">单独设置</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item v-if="formData!.subCommissionType">
      <section>
        <el-table :data="formData!.skus">
          <el-table-column align="center" label="一级返佣类型" min-width="168">
            <template #default="{ row }">
              <el-select
                v-model="row.firstBrokerageType"
                disabled
                placeholder="请选择返佣类型"
                class="w-100%!"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_SETTLEMENT_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="center" label="一级返佣" min-width="168">
            <template #default="{ row }">
              <el-input-number
                v-if="row.firstBrokerageType == 2"
                v-model="row.firstBrokeragePrice"
                :min="0"
                :precision="2"
                :step="0.1"
                class="w-100%!"
                :controls="false"
              >
                <template #suffix>
                  <span>元</span>
                </template>
              </el-input-number>
              <el-input
                v-if="row.firstBrokerageType == 1"
                v-model="row.firstBrokeragePercent"
                :max="100"
                :formatter="verifyNumberPercentage"
                :min="0"
                :precision="0"
                :step="1"
                class="w-100%!"
                :controls="false"
              >
                <template #suffix>
                  <span>%</span>
                </template>
              </el-input>
            </template>
          </el-table-column>

          <el-table-column align="center" label="二级返佣类型" min-width="168">
            <template #default="{ row }">
              <el-select
                v-model="row.secondBrokerageType"
                disabled
                placeholder="请选择返佣类型"
                class="w-100%!"
              >
                <el-option
                  v-for="dict in getIntDictOptions(DICT_TYPE.PRODUCT_SETTLEMENT_TYPE)"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column align="center" label="二级返佣" min-width="168">
            <template #default="{ row }">
              <el-input-number
                v-if="row.secondBrokerageType == 2"
                v-model="row.secondBrokeragePrice"
                :min="0"
                :precision="2"
                :step="0.1"
                class="w-100%!"
                :controls="false"
              >
                <template #suffix>
                  <span>元</span>
                </template>
              </el-input-number>
              <el-input
                v-if="row.secondBrokerageType == 1"
                v-model="row.secondBrokeragePercent"
                :formatter="verifyNumberPercentage"
                :max="100"
                :min="0"
                :precision="0"
                :step="1"
                class="w-100%!"
                :controls="false"
              >
                <template #suffix>
                  <span>%</span>
                </template>
              </el-input>
            </template>
          </el-table-column>
        </el-table>
      </section>
    </el-form-item>
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>销量设置</span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px">
        如商品在线下渠道有销售，可以填写该商品在线下渠道的销售数据。线上展示销量数据为线下销量+线上销量之和。
      </span>
    </div>
    <el-form-item label="线下销量" prop="virtualSalesCount">
      <el-input-number
        v-model="formData.virtualSalesCount"
        @change="virtualSalesCountChange"
        :min="0"
        placeholder="请输入线下销量"
        class="w-80!"
      />
    </el-form-item>
  </el-form>
</template>
<script lang="ts" setup>
import { PropType } from 'vue'
import { copyValueToTarget, generateNumericUUID } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import {
  getPropertyList,
  PropertyAndValues,
  ProductSpuTypeSelect
} from '@/views/mall/product/spu/components/index'
import type { Spu } from '@/api/mall/product/spu'
import GiveGoodsForm from '@/views/mall/product/spuPaidMember/components/GiveGoodsForm.vue'
// import GiveGoodsForm from '../../components/GiveGoodsForm.vue'
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { verifyNumberPercentage, verifyNumberIntegerAndFloat } from '@/utils/formatter'

defineOptions({ name: 'ProductSpuValueCardSkuForm' })

const message = useMessage() // 消息弹窗

const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  isDetail: propTypes.bool.def(false), // 是否作为详情组件
  activeName: propTypes.string.def('sku')
})
const formRef = ref() // 表单 Ref
const propertyList = ref<PropertyAndValues[]>([]) // 商品属性列表
const skuListRef = ref() // 商品属性列表 Ref
const formData = reactive<Spu>({
  spuType: 4,
  specType: false, // 商品规格
  spuId: undefined,
  virtualSalesCount: 0,
  skus: [
    {
      price: 0, //零售价
      costPrice: 0, //成本价
      cardValue: 0, // 储值卡|金额
      useDiscountType: [], //储值卡 使用折扣类型
      allDiscount: 0, //全部商品折扣
      appointTypeDiscount: {}, //指定商品类型
      appointSkusDiscount: {}, //储值卡 指定商品规则
      expiryDate: '', //有效期
      expiryDateUnit: 0, //有效期单位
      isDebtSales: false, //欠款销售
      isGift: false, //是否赠金
      giftValue: 0, // 赠送金额
      dedLevel: undefined, //扣款优先
      giftAccountType: 0, //赠金到账 0一次到账 1周期到账
      giftAccountDType: undefined, //到账方式 0统一 1单一设置
      firstBrokeragePercent: 0, // 一级分销的佣金 比例
      secondBrokeragePercent: 0, // 二级分销的佣金 比例
      firstBrokerageType: 2, // 一级分销的佣金类型
      secondBrokerageType: 2, // 二级分销的佣金类型
      firstBrokeragePrice: 0, // 一级分销的佣金
      secondBrokeragePrice: 0, // 二级分销的佣金
      skuType: 1,
      skuId: generateNumericUUID() //商品 SKU 编号

      // giveGoods: {}
    }
  ]
})
/**虚拟销量 */
const virtualSalesCountChange = () => {
  Object.assign(props.propFormData, formData)
}
/** 分销类型 */
const changeSubCommissionEnable = () => {
  formData.subCommissionType = false
  Object.assign(props.propFormData, formData)
}
const changeSubCommissionType = () => {
  // 默认为零，类型切换后也要重置为零
  for (const item of formData.skus!) {
    item.firstBrokeragePrice = 0
    item.secondBrokeragePrice = 0
  }
  Object.assign(props.propFormData, formData)
}
const rules = reactive({
  price: [{ required: true, message: '请输入零售价', trigger: 'blur' }],
  cardValue: [{ required: true, message: '请输入储值卡金额', trigger: 'blur' }],
  expiryDate: [{ required: true, message: '请输入有效期', trigger: 'blur' }],
  giftValue: [{ required: true, message: '请输入赠送金额', trigger: 'blur' }],
  dedLevel: [{ required: true, message: '请选择扣款顺序', trigger: 'change' }]
})
const objectToArray = (obj) => {
  return Object.keys(obj).map(function (key) {
    return { typeId: key, discount: obj[key].discount }
  })
}

const arrayToObject = (arr) => {
  return arr.reduce(function (obj, item) {
    obj[item.typeId] = {
      discount: item.discount
    }
    return obj
  }, {})
}
/** 储值卡折扣 商品类型 */
const SpuTypeSelectRef = ref()
const typeDiscountGoods = ref<any>([])
const typeDiscount = ref<any>([])
const typeDiscountGoodsChange = (value) => {
  typeDiscount.value = []
  value.forEach((item) => {
    const row = {
      typeId: item,
      discount: 100
    }
    typeDiscount.value.push(row)
  })
  if (JSON.stringify(formData.skus![0].appointTypeDiscount) != '{}') {
    // 如果有输入的值就回显
    let arr = objectToArray(formData.skus![0].appointTypeDiscount)

    arr.forEach((element) => {
      typeDiscount.value.forEach((ele) => {
        if (ele.typeId == element.typeId) ele.discount = element.discount
      })
    })
  } else {
  }
  formData.skus![0].appointTypeDiscount = arrayToObject(typeDiscount.value)
}
const getSputTypeInfo = (value) => {
  if (!value) {
    return
  }
  let text = ''
  let panelList = SpuTypeSelectRef.value[0].getCheckedNodes()
  // return panelList.find((ele) => {
  //   return ele.value == value
  // })
  panelList.filter((panelItem) => {
    if (panelItem.value == value) {
      text = panelItem.text
    }
  })
  return text
  // return info
}
/** 周期到账类型*/
const giftAccountDTypeChange = (item) => {
  item.giftAccountSet = [
    {
      intoAccountDateDay: '',
      intoAccountDateMonth: ''
    }
  ]
}
const giftAccountDTypeAdd = (giftAccountSet) => {
  giftAccountSet.push({
    intoAccountDateDay: '',
    intoAccountDateMonth: ''
  })
}
const giftAccountDTypeDelete = (giftAccountSet, index) => {
  if (index == 0) {
    message.warning('单一设置必须保留一项')
    return
  }
  giftAccountSet.splice(index, 1)
}

const monthGiveRollDateOptions = computed(() => {
  const arr = [] as EmptyArrayType
  for (let i = 1; i <= 31; i++) {
    arr.push({
      label: i,
      value: i
    })
  }
  return arr
})

onMounted(() => {})
/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }
    copyValueToTarget(formData, data)
    typeDiscountGoods.value = []
    Object.keys(formData.skus![0].appointTypeDiscount).map(function (key) {
      typeDiscountGoods.value.push(Number(key))
    })

    // typeDiscountGoodsChange(typeDiscountGoods.value)
    // 将 SKU 的属性，整理成 PropertyAndValues 数组
    propertyList.value = getPropertyList(data)
  },
  {
    // deep: true,
    immediate: true
  }
)
// 关联商品校验信息
const giveGoodsFormErrorInfo = ref('')
const setgiveGoodsFormErrorInfo = (errorInfo) => {
  if (errorInfo) {
    giveGoodsFormErrorInfo.value = errorInfo
  } else {
    giveGoodsFormErrorInfo.value = errorInfo
  }
}
/** 表单校验 */
const discountGiveGoodsFormRef = ref() //储值卡折扣指定商品

const emit = defineEmits(['update:activeName'])
const validate = async () => {
  if (!formRef) return
  try {
    // 校验 sku
    skuListRef.value?.validateSku()
    // 校验需要判断
    ;(await unref(discountGiveGoodsFormRef)) && unref(discountGiveGoodsFormRef)[0].validate()

    await unref(formRef).validate()

    // 校验通过更新数据
    Object.assign(props.propFormData, formData)
  } catch (e) {
    message.error('【储值卡信息】不完善，请填写相关信息')
    emit('update:activeName', 'sku')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })
</script>
